<?php

namespace app\common\model\service;

use app\common\model\coupon\Log;
use app\common\model\Evaluation;
use app\common\model\Hospital;
use app\common\model\Phone;
use app\common\model\phone\Data;
use app\common\model\ScoreLog;
use app\common\model\Service;
use app\common\model\service\order\Info;
use app\common\model\ServiceCategory;
use app\common\model\User;
use app\common\model\user\Jz;
use think\Log as ThinkLog;
use think\Model;


class Order extends Model
{





    // 表名
    protected $name = 'service_order';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'endtime_text',
        'servicetime_text',
        'canceltime_text',
        'qx_time',
        'createtime_text',
        'status_text',
        'order_type',
        'service_type',
        'total_commission',
        'renew_info',
        'pl_btn',
        'json_array'
    ];

    public function getJsonArrayAttr($value, $data)
    {
        return !empty($data['json']) ? json_decode(htmlspecialchars_decode($data['json']), true) : '';
    }

    public function getRenewInfoAttr($value, $data)
    {
        if (!isset($data['escort_id'])) {
            return ['is_renew' => 0];
        }
        if ($info = Info::whereNull('paytime')->where('order_id', $data['id'])->find()) {
            if (!$data['escort_id']) {
                return ['is_renew' => 0];
            }
            if ($data['category_id'] ?? 0) {
                $service_type = ServiceCategory::get($data['category_id'] ?? 0)['name'];
            } else {
                $service_type = Service::get($data['cate_id'])['title'];
            }

            $user = User::get($data['escort_id']);
            $map = [
                'is_renew' => 1,
                'id' => $info['id'],
                'service_type' => $service_type,
                'realname' => $user['realname'],
                'time' => $info['time'],
                'money' => bcdiv($info['renewal_amount'], $info['time'], 2),
                'total_money' => $info['renewal_amount']
            ];
            return $map;
        } else {
            return ['is_renew' => 0];
        }
    }

    public function getTotalCommissionAttr($value, $data)
    {

        if (isset($data['escort_id']) && $data['escort_id']) {
            $escort = User::get($data['escort_id']);
            if ($escort) {
                return number_format($data['total_amount'] * $escort['proportion'] / 100, 2);
            }
        }
        return 0;
    }


    public function getOrderTypeAttr($value, $data)
    {
        return Service::get($data['cate_id'])['title'] ?? '';
    }

    public function getServiceTypeAttr($value, $data)
    {
        return ServiceCategory::get($data['category_id'] ?? 0)['name'] ?? '';
    }
    public function getQxTimeAttr($value, $data)
    {
        $time = $data['createtime'] + 1800 - time();
        return $time > 0 ? $time : 0;
    }


    public function getStatusList()
    {
        //订单状态:0=待支付,1=待雇佣,2=待开始,3=待验收,4=已完成,-1已取消
//        return ['0' => __('待支付'), '1' => __('待雇佣'), '2' => __('待开始'), '3' => __('待验收'),  '4' => __('已完成'), '-1' => __('已取消')];
         return ['0' => __('待支付'), '1' => __('待雇佣'), '5' => __('待接单'), '2' => __('待开始'), '3' => __('待验收'), '4' => __('已完成'), '-1' => __('已取消')];
    }


    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function getEndtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['endtime']) ? $data['endtime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getServicetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['servicetime']) ? $data['servicetime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCanceltimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['canceltime']) ? $data['canceltime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['status']) ? $data['status'] : '');
        $list = $this->getStatusList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    protected function setEndtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setServicetimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCanceltimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }


    public function refuse()
    {
        return $this->hasMany('app\common\model\service\order\Refuse', 'order_id', 'id');
    }

    public function info()
    {
        return $this->hasMany('app\common\model\service\order\Info', 'order_id', 'id');
    }

    public function getPlBtnAttr($value, $data)
    {
        return Evaluation::where('order_id', $data['id'])->count();
    }

    public function coupon()
    {
        return $this->belongsTo('app\common\model\coupon\Log', 'coupon_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function escort()
    {
        return $this->belongsTo('app\common\model\User', 'escort_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function user()
    {
        return $this->belongsTo('app\common\model\User', 'user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function jz()
    {
        return $this->belongsTo('app\common\model\user\Jz', 'jz_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function city()
    {
        return $this->belongsTo('app\common\model\City', 'city_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function hospital()
    {
        return $this->belongsTo('app\common\model\Hospital', 'hospital_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }

    public function service()
    {
        return $this->belongsTo('app\common\model\Service', 'cate_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public function category()
    {
        return $this->belongsTo('Category', 'category_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
    public static function addOrder($data, $service)
    {
        extract($data);
        $params['total_amount'] = $params['pay_amount'] = $service->price;
        $params['total_sn'] = sn('service_order', 'total_sn', 'SO');
        $params['deduction_amount'] = $params['coupon_amount'] = 0;
        $params['content'] = $content ?? '';
//        if ($service->category_ids) {
//            $service_category = ServiceCategory::get($category_id);
//            $params['total_amount'] = $params['pay_amount'] = $service_category->price;
//        }

        if (isset($coupon_id) && $coupon_id && Log::get($coupon_id)) {
            $res = Log::useCoupon($coupon_id, $params['pay_amount']);
            $params['coupon_amount'] = $res['coupon_amount'];
            $params['pay_amount'] = $res['pay_amount'];
            $params['coupon_id'] = $coupon_id;
        }
        if ($point == 1) {
            $user = User::get($user_id);
            $credit_points = config('site.credit_points');
            $maxScore = bcmul($params['pay_amount'], $credit_points, 0);

            $int = bcdiv($user->score, $credit_points, 0);
            $useScore = bcmul($int, $credit_points, 0);


            if ($useScore >= $maxScore) {
                $useScore = $maxScore;
            }
            $num = bcdiv($useScore, $credit_points, 0);

            if ($user->score < $useScore) {
                exception('积分不足', null, 20001);
            }
            $params['deduction_amount'] = $num;
            $params['pay_amount'] = $params['pay_amount'] - $num;
            if ($useScore) {
                ScoreLog::income($user_id, $useScore, 1, 100, $params['total_sn']);
            }

        }

        $params['city_id'] = $city_id;
        $params['user_id'] = $user_id;
//        $params['category_id'] = $category_id;
        $params['cate_id'] = $cate_id;
        $params['jz_id'] = $jz_id;
        $params['actiontime'] = $actiontime;
//        $params['hospital_id'] = $hospital_id;
        $params['json'] = $json;

        $model = new self;
        $model->allowField(true)->save($params);
        return $model;
    }
    //取消订单
    public static function cancelOrder($order, $transaction_id = '')
    {
        $res = self::where('id', $order['id'])->update(['status' => '-1', 'canceltime' => time(), 'refund_transaction_id' => $transaction_id]);

        //订单取消退回优惠券
        if ($order['coupon_id']) {
            Log::update(['status' => '1'], ['id' => $order['coupon_id']]);
        }
        //订单取消退回积分
        $score_log = ScoreLog::get(['order_sn' => $order['total_sn'], 'source_type' => 100]);
        if ($score_log) {
            ScoreLog::income($score_log->user_id, $score_log->score, 2, 101, $order['total_sn']);
        }
//        Order::unbind_telephone($order->escort->mobile, $order->user->mobile, $order->id);
//        ThinkLog::error('取消订单：' . $res);

        return $res ? true : false;
    }
    //绑定虚拟号码
    public static function bing_telephone($bindNumberA, $bindNumberB, $order_id)
    {
        return 1333333333;
        $phone = rand_phone($bindNumberA, $bindNumberB);
        if ($phone['code'] == 0) {
            Data::create([
                'phone' => $phone['phone'],
                'bindNumberA' => $bindNumberA,
                'bindNumberB' => $bindNumberB,
                'order_id' => $order_id,
            ]);
            return $phone['phone'];
        } else {
            $dh = new Phone();
            if ($phone['code'] == 2) {
                $dh->whereNotIn('phone', $phone['phone']);
            }
            $moblie = $dh->value('phone');
            $sig = md5('996147' . '4eeb258d50424c07bfc3a08fd4c63a35' . msectime());
            $tokenUrl = 'https://101.37.133.245:11008/voice/1.0.0/middleNumberAXB/996147/' . $sig;
            $Authorization = base64_encode('996147' . ':' . msectime());
            $header  = array(
                'Accept: application/json',
                'Content-Type: application/json',
                'Authorization:' . $Authorization,
            );
            $data = [
                'middleNumber' => $moblie,
                'bindNumberA' => $bindNumberA,
                'bindNumberB' => $bindNumberB,
            ];
            $data = json_encode($data);
            $res = curl_post_https($tokenUrl, $data, $header);
            $data = json_decode($res, true);
            if ($data['result'] == '000000') {
                Data::create([
                    'phone' => $moblie,
                    'bindNumberA' => $bindNumberA,
                    'bindNumberB' => $bindNumberB,
                    'order_id' => $order_id,
                ]);
                return $data['middleNumber'];
            } else {
                exception($data['message']);
            }
        }
    }
    //解绑虚拟号码
    public static function unbind_telephone($bindNumberA, $bindNumberB, $order_id)
    {
        return true;

        $order = Order::get($order_id);
        $sig = md5('996147' . '4eeb258d50424c07bfc3a08fd4c63a35' . msectime());
        $tokenUrl = 'https://101.37.133.245:11008/voice/1.0.0/middleNumberUnbind/996147/' . $sig;
        $Authorization = base64_encode('996147' . ':' . msectime());
        $header  = array(
            'Accept: application/json',
            'Content-Type: application/json',
            'Authorization:' . $Authorization,
        );
        $data = [
            'middleNumber' => $order->virtual_telephone,
            'bindNumberA' => $bindNumberA,
            'bindNumberB' => $bindNumberB,
        ];
        $data = json_encode($data);
        $res = curl_post_https($tokenUrl, $data, $header);
        $data = json_decode($res, true);
        if ($data['result'] == '000000') {
            Data::where('order_id', $order_id)->delete();
            return true;
        } else {
            exception($data['message']);
        }
    }
}
